/******************************************************************
 * @version      : 1.0
 * @Author       : zhl
 * @Date         : 2023-03-16 09:55:08
 $ @LastEditors: zhl
 * @E-Mail       : zhll168@163.com
 * @Description  : 业务描述
 ******************************************************************/
#include "NetManager.h"
#include "CLogger.h"
#include <thread>

NetManager NetManager::c_tcp_manager;

NetManager::NetManager(/* args */){
    mg_log_set(MG_LL_INFO);  // Set log level
    mg_mgr_init(&c_mgr);        // Initialize event manager
}

NetManager::~NetManager(){
    close();
}

int  NetManager::connect(){
    return 0;
}

NetManager& NetManager::getInstance(){
    return c_tcp_manager;
}

static void net_poll(struct mg_mgr* mgr){
    if(NULL == mgr){
        return ;
    }
    while(true){
        mg_mgr_poll(mgr, 1000);
    }
}

int  NetManager::init(std::weak_ptr<CConfigManager> cm, const char* ip, uint16_t port, WORKING_MODE mode){
    int ret = -1;
    c_tcp_if = std::make_shared<TCPInterface>();
    c_tcp_if->init(cm, &c_mgr);
    switch(mode){
        case WORKING_MODE_CLIENT:
            ret = c_tcp_if->connect(ip, port);
        break;
        case WORKING_MODE_SERVER:
            ret = c_tcp_if->listen(ip, port);
        break;
        default:
            ret = c_tcp_if->listen(ip, port);
        break;
    }
    if(0 == ret){
        std::thread np(net_poll, &c_mgr);
        np.detach();
    }
    return ret;        
}

int  NetManager::send(const char *buf, int len){
    return c_tcp_if->send(buf, len);
}

void NetManager::close(){
    mg_mgr_free(&c_mgr);
}

